package com.leyou.user.web;

import com.leyou.common.exception.LyException;
import com.leyou.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-06-05 12:40
 **/
@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone")String phone) {

        userService.sendVerifyCode(phone);
        return ResponseEntity.status(HttpStatus.OK).build();

    }

    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> judgeUser(@PathVariable("data") String data,
                                             @PathVariable("type")Integer type){
        Boolean flag = userService.judgeUser(data, type);
        return ResponseEntity.ok(flag);
    }

    @PostMapping
    public ResponseEntity<Void> registerUser(@Valid User user, BindingResult result, @RequestParam("code")String code) {
        if (result.hasErrors()) {
            String errorMsg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
            System.out.println(errorMsg);
            throw new LyException(400, "请求参数错误");
        }
        userService.registeUser(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping
    public ResponseEntity<UserDTO> queryUserByNameAndPassword(@RequestParam("username")String username,
                                                           @RequestParam("password")String password) {

        UserDTO userDTO = userService.queryUserByNameAndPassword(username, password);
        return ResponseEntity.ok(userDTO);
    }
}
